﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microhard.WarehouseInsp.Buz.Interfaces;
using Microhard.Core.DBUtility;
using Microhard.WarehouseInsp.Buz.DataAccess;
using Microhard.WarehouseInsp.Buz.DTO;
using Microhard.Core;
using Microhard.WarehouseInsp.Buz.Msg;
using Microhard.WarehouseInsp.Buz.Models;
using Microhard.WarehouseInsp.Buz.BuzEnum;
using Microhard.WarehouseInsp.Buz.JHWorkflow;

namespace Microhard.WarehouseInsp.Buz.Impls
{
    public class InspectionRecordImpl : IInspectionRecord
    {

        public Microhard.Core.DBUtility.ExecutedResult Add(InspectionRecordModel model)
        {
            ExecutedResult rtn = new ExecutedResult();
            WarehouseInspEntities db = new WarehouseInspEntities();
            var entity = db.Warehouses.SingleOrDefault(l => l.WarehouseID == model.WarehouseID);
            model.CreateTime = DateTime.Now;
            model.CreatorID = scope.CurrentUserID.ToString();
            model.CreatorName = scope.CurrentUserRealName;
            model.WarehouseName = entity.Name;

            var op = model.ToEntity();
            try
            {
                db.InspectionRecords.AddObject(op);
                db.SaveChanges();
                //实盘货值低于监管底线，提醒
                var guidline = db.SupervisionDetails.Where(p => p.ProjectID == model.PrjID && p.Status == (int)PrjStatus.Finished)
                    .OrderByDescending(d => d.CreateTime).First();
                if (guidline.Guardline >= model.CurrentAmountIByChecking)
                {
                    //发送提醒
                    StringBuilder content = new StringBuilder();
                    content.Append("项目:" + model.PrjName);
                    content.Append(",实盘货值:" + model.CurrentAmountIByChecking);
                    content.Append(",监管底线:" + guidline.Guardline);
                    content.Append("实盘货值低于监管底线,请注意");
                    SendAlertByJH.SendAlert(model.PrjID, content.ToString());
                }
            }
            catch (System.Exception ex)
            {
                rtn.ErrorMsg.Add(DBOperationFailedStatus.AddFailed, WarehouseMsg.AddFailed);
                Log.Error("IInspectionRecord.Add", ex);
            }

            return rtn;
        }

        public Microhard.Core.DBUtility.ExecutedResult Update(InspectionRecordModel model)
        {
            ExecutedResult result = new ExecutedResult();
            WarehouseInspEntities db = new WarehouseInspEntities();
            try
            {
                var entity = db.InspectionRecords.SingleOrDefault(l => l.InspectionRecordID == model.InspectionRecordID);
                if (entity != null)
                {
                    entity.InsEmployeeName = model.InsEmployeeName;
                    entity.InsEmployeePhone = model.InsEmployeePhone;
                    entity.InsDatetime = model.InsDatetime;
                    entity.PledePrdDescription = model.PledePrdDescription;
                    entity.Enviro = model.Enviro;
                    entity.Inquement = model.Inquement;
                    entity.Process = model.Process;
                    entity.Att = model.Att;
                    entity.LowLevel = model.LowLevel;
                    entity.CurrentAmountInSheet = model.CurrentAmountInSheet;
                    entity.CurrentAmountIByChecking = model.CurrentAmountIByChecking;
                    entity.EnterpriseType = model.EnterpriseType;
                    entity.PrjID = model.PrjID;
                    entity.PrjName = model.PrjName;
                    db.SaveChanges();

                    //实盘货值低于监管底线，提醒
                    var guidline = db.SupervisionDetails.Where(p => p.ProjectID == model.PrjID && p.Status == (int)PrjStatus.Finished)
                        .OrderByDescending(d => d.CreateTime).First();
                    if (guidline.Guardline >= model.CurrentAmountIByChecking)
                    {
                        //发送提醒
                        StringBuilder content = new StringBuilder();
                        content.Append("项目:" + model.PrjName);
                        content.Append(",巡检员:" + guidline.SupProject.ProtalEmpName);
                        content.Append(",数据专员:" + guidline.SupProject.PMName);
                        content.Append(",实盘货值:" + model.CurrentAmountIByChecking.ToString("f2"));
                        content.Append(",监管底线:" + guidline.Guardline.Value.ToString("f2"));
                        content.Append(",实盘货值低于监管底线,请注意");
                        SendAlertByJH.SendAlert(model.PrjID, content.ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                result.ErrorMsg.Add(DBOperationFailedStatus.UpdateFailed, WarehouseMsg.UpdateFailed);
                Log.Error("IInspectionRecord.Update", ex);
            }
            return result;
        }

        public Microhard.Core.DBUtility.ExecutedResult Delete(List<Guid> ids)
        {
            ExecutedResult result = new ExecutedResult();
            WarehouseInspEntities db = new WarehouseInspEntities();
            var entity = db.InspectionRecords.Where(l => ids.Contains(l.InspectionRecordID));
            foreach (var e in entity)
            {

                try
                {
                    db.InspectionRecords.DeleteObject(e);
                }
                catch
                {
                    result.ErrorMsg.Add(DBOperationFailedStatus.DeleteFailed, "无法删除");
                }
            }
            if (result.ErrorMsg.Count == 0)
            {
                try
                {
                    db.SaveChanges();
                }
                catch (Exception ex)
                {
                    result.ErrorMsg.Add(DBOperationFailedStatus.DeleteFailed, WarehouseMsg.DeleteFailed);
                    Log.Error("IInspectionRecord.Delete", ex);
                }
            }
            return result;
        }

        public Microhard.Core.DBUtility.ExecutedResult Delete(InspectionRecordModel model)
        {
            throw new NotImplementedException();
        }

        public InspectionRecordModel GetModelByID(Guid id)
        {
            WarehouseInspEntities db = new WarehouseInspEntities();
            var mcmp = db.InspectionRecords.SingleOrDefault(c => c.InspectionRecordID == id);
            if (mcmp != null)
            {
                return mcmp.ToModel();
            }
            return null;
        }

        public InspectionRecordModel GetModelByModel(InspectionRecordModel model)
        {
            throw new NotImplementedException();
        }

        public List<InspectionRecordModel> Query(InspectionRecordModel Model, int pageIndex, int pageSize, out int totalCount)
        {
            WarehouseInspEntities db = new WarehouseInspEntities();

            IEnumerable<InspectionRecord> entities = (from b in db.InspectionRecords
                                                      where this.scope.PKID.Contains(b.InspectionRecordID)
                                                      select b).ToList();
            totalCount = entities.Count();
            var pagedEntities = entities.OrderByDescending(p => p.CreateTime).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            if (pagedEntities != null && pagedEntities.Count > 0)
            {
                var dat = pagedEntities.Select(m => m.ToModel()).ToList();
                foreach (var w in dat)
                {
                    var attachmentList = from b in db.Attachments
                                         where b.MainDataID == w.InspectionRecordID
                                         select new { AttachmentID = b.AttachmentID, Name = b.Name };
                    w.FileList = new List<AttachmentModel>();
                    if (attachmentList.Count() > 0)
                    {
                        foreach (var en in attachmentList)
                        {
                            AttachmentModel a = new AttachmentModel();
                            a.AttachmentID = en.AttachmentID;
                            a.Name = en.Name;
                            w.FileList.Add(a);
                        }
                    }
                }
                return dat;
            }
            return new List<InspectionRecordModel>();
        }


        public List<InspectionRecordModel> Query(InspectionRecordModel Model)
        {
            throw new NotImplementedException();
        }

        public Microhard.Core.DBUtility.ScopeResult scope
        {
            set;
            get;
        }
    }
}
